from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings

from carts.utils import merge_cart_cookie_to_redis
from oauth.exceptions import QQAPIError
from oauth.models import OauthQQuser
from oauth.serializers import OAuthQQUserSerializer
from oauth.utils import OAuthQQ


class QQAuthURLView(APIView):

    """QQ登录"""
    def get(self,request):
        # 获取next
        next = request.query_params.get('next')
        oauth = OAuthQQ()
        login_url = oauth.get_qq_login_url(next)
        return Response({"login_url":login_url})


class QQAuthUserView(CreateAPIView):
    serializer_class = OAuthQQUserSerializer

    """
    1.通过code，获取access_token
    2.通过access_token　获取ｏｐｅｎｉｄ
    3.判断用户是否第一次登陆,若果不是第一次登陆，返回ｔｏｋｅｎ，若是第一次登陆返回信息
    """
    def get(self,request):
        code = request.query_params.get('code')

        if not code:
            return Response({'message':'缺少code'},status=status.HTTP_503_SERVICE_UNAVAILABLE)

        oauthqq = OAuthQQ()
        try:
            access_token = oauthqq.get_access_token(code)
            openid = oauthqq.get_openid(access_token)
        except QQAPIError:
            return Response({'message': 'QQ服务异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        try:
            qq_user = OauthQQuser.objects.get(openid=openid)
        except OauthQQuser.DoesNotExist:
            # 用户第一次使用QQ登录
            token = oauthqq.generate_save_user_token(openid)
            return Response({'access_token': token})
        else:
            # 找到用户, 生成token
            print(qq_user)
            user = qq_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            response = Response({
                'token': token,
                'user_id': user.id,
                'username': user.username
            })
            response = merge_cart_cookie_to_redis(request, user, response)
            return response

    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)

        # 合并购物车
        user = self.user
        response = merge_cart_cookie_to_redis(request, user, response)
        return response





